package com.htjx.mall.services;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;

import com.htjx.mall.admin.controllers.vo.BrandQuery;
import com.htjx.mall.commons.mappers.BrandMapper;
import com.htjx.mall.commons.models.enums.SeqType;
import com.htjx.mall.commons.models.product.Brand;
import com.htjx.mall.commons.utils.page.Page;

@Service
public class BrandService {
	@Autowired
	private BrandMapper brandMapper; 
	@Autowired
	private SequenceManager sequenceManager;
	@Autowired
	private TransactionTemplate transactionTemplate;
	
	public List<Brand> selectByActive(boolean active) {
		return brandMapper.selectByActive(active);
	}
	
	public void insertOne(final Brand brand) {
		long[] seq = sequenceManager.buildBatchSeq(SeqType.Brand, 1);
		brand.setId(seq[0]);
		transactionTemplate.execute(new TransactionCallbackWithoutResult() {
			@Override
			protected void doInTransactionWithoutResult(TransactionStatus status) {
				brandMapper.insertOne(brand);
			}
		});
	}
	
	public Brand selectById(long id) {
		return brandMapper.selectOne(id);
	}
	
	public void updateOne(final Brand brand) {
		transactionTemplate.execute(new TransactionCallbackWithoutResult() {
			@Override
			protected void doInTransactionWithoutResult(TransactionStatus status) {
				brandMapper.updateOne(brand);
			}
		});
	}
	
	public void deleteOne(final long id) {
		transactionTemplate.execute(new TransactionCallbackWithoutResult() {
			@Override
			protected void doInTransactionWithoutResult(TransactionStatus status) {
				brandMapper.deleteOne(id);
			}
		});
	}
	
	public Page<Brand> page(BrandQuery brandQuery, Page<Brand> page) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("offset", page.getFirst() - 1);
		params.put("size", page.getPageSize());
		params.put("brandQuery", brandQuery);
		List<Brand> result = brandMapper.page(params);
		page.setResult(result);
		if (page.isAutoCount()) {
			int totalCount = brandMapper.pageCount(params);
			page.setTotalCount(totalCount);
		}
		return page;
	}
	
	/**
	 * 检测唯一属性
	 */
	public boolean checkUniqueByProperty(String propertyName, String propertyValue) {
		return !brandMapper.selectByProperty(propertyName, propertyValue).isEmpty();
	}
	
	public Brand findUniqueBy(String propertyName, String propertyValue) {
		List<Brand> list = brandMapper.selectByProperty(propertyName, propertyValue);
		if (list.isEmpty()) {
			return null;
		}
		if (list.size() == 1) {
			return list.get(0);
		}
		throw new RuntimeException("there are too many rows, actual " + list.size());
	}
}
